﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Diagnostics;
using ATEGo;
using MesServices;
using System.Text.RegularExpressions;


namespace Degrade
{
    public partial class DegradeForm : Form, IExecutorForm
    {
        #region 变量
        /// <summary>
        /// 配置文件类
        /// </summary>
        private Setting Setting;
        /// <summary>
        /// 配置文件的地址
        /// </summary>
        private readonly string SettingPath = "Data\\Setting.json";
        /// <summary>
        /// Log地址
        /// </summary>
        private readonly string LogPath = "Data\\Log\\";
        /// <summary>
        /// 最大线程数
        /// </summary>
        private readonly int ThreadNum = 5;
        //组控件
        private List<ComboBox> Group_CB_Cabinet = new List<ComboBox>();
        private List<ProgressBar> Group_PB = new List<ProgressBar>();
        private List<Label> Group_LB_ProgressValue = new List<Label>();
        private List<Button> Group_BT_Start = new List<Button>();
        private List<Button> Group_BT_Stop = new List<Button>();
        private List<Label> Group_LB_TimeCount = new List<Label>();
        private List<TextBox> Group_TB_IP_Telnet = new List<TextBox>();
        private List<TextBox> Group_TB_IP_SSH = new List<TextBox>();
        private List<RichTextBox> Group_RTB_Log_Flow = new List<RichTextBox>();
        private List<RichTextBox> Group_RTB_Log_Cmd = new List<RichTextBox>();
        private List<TextBox> Group_TB_FtpServer = new List<TextBox>();
        private List<TextBox> Group_TB_Package = new List<TextBox>();
        private List<TextBox> Group_TB_MES = new List<TextBox>();
        private List<CheckBox> Group_CB_Management = new List<CheckBox>();
        private List<System.Windows.Forms.Timer> Group_Timer = new List<System.Windows.Forms.Timer>();
        private List<RadioButton> Group_RB_ProductIP = new List<RadioButton>();
        private List<TextBoxBase> Group_TB_SSH = new List<TextBoxBase>();
        /// <summary>
        /// 执行器
        /// </summary>
        private List<Executor> Group_Executors = new List<Executor>();
        #endregion

        #region 界面初始化和结束
        public DegradeForm()
        {
            InitializeComponent();
            //设置窗体的固定大小
            this.Size = new Size(1320,850);
            //反序列化json配置
            string temp = File.ReadAllText(SettingPath);
            Setting = JsonConvert.DeserializeObject<Setting>(temp);
            //给组控件赋值
            Group_CB_Cabinet.Add(cabinet1);
            Group_CB_Cabinet.Add(cabinet2);
            Group_CB_Cabinet.Add(cabinet3);
            Group_CB_Cabinet.Add(cabinet4);
            Group_CB_Cabinet.Add(cabinet5);
            Group_PB.Add(progressBar1);
            Group_PB.Add(progressBar2);
            Group_PB.Add(progressBar3);
            Group_PB.Add(progressBar4);
            Group_PB.Add(progressBar5);
            Group_LB_ProgressValue.Add(Prg_Value1);
            Group_LB_ProgressValue.Add(Prg_Value2);
            Group_LB_ProgressValue.Add(Prg_Value3);
            Group_LB_ProgressValue.Add(Prg_Value4);
            Group_LB_ProgressValue.Add(Prg_Value5);
            Group_BT_Start.Add(Start1);
            Group_BT_Start.Add(Start2);
            Group_BT_Start.Add(Start3);
            Group_BT_Start.Add(Start4);
            Group_BT_Start.Add(Start5);
            Group_BT_Stop.Add(Stop1);
            Group_BT_Stop.Add(Stop2);
            Group_BT_Stop.Add(Stop3);
            Group_BT_Stop.Add(Stop4);
            Group_BT_Stop.Add(Stop5);
            Group_LB_TimeCount.Add(Time1);
            Group_LB_TimeCount.Add(Time2);
            Group_LB_TimeCount.Add(Time3);
            Group_LB_TimeCount.Add(Time4);
            Group_LB_TimeCount.Add(Time5);
            Group_Timer.Add(timer1);
            Group_Timer.Add(timer2);
            Group_Timer.Add(timer3);
            Group_Timer.Add(timer4);
            Group_Timer.Add(timer5);
            Group_TB_IP_Telnet.Add(telnet_client_ip1);
            Group_TB_IP_Telnet.Add(telnet_client_ip2);
            Group_TB_IP_Telnet.Add(telnet_client_ip3);
            Group_TB_IP_Telnet.Add(telnet_client_ip4);
            Group_TB_IP_Telnet.Add(telnet_client_ip5);
            Group_TB_IP_SSH.Add(ssh_client_ip1);
            Group_TB_IP_SSH.Add(ssh_client_ip2);
            Group_TB_IP_SSH.Add(ssh_client_ip3);
            Group_TB_IP_SSH.Add(ssh_client_ip4);
            Group_TB_IP_SSH.Add(ssh_client_ip5);
            Group_RTB_Log_Flow.Add(Flowlog1);
            Group_RTB_Log_Flow.Add(Flowlog2);
            Group_RTB_Log_Flow.Add(Flowlog3);
            Group_RTB_Log_Flow.Add(Flowlog4);
            Group_RTB_Log_Flow.Add(Flowlog5);
            Group_RTB_Log_Cmd.Add(Cmdlog1);
            Group_RTB_Log_Cmd.Add(Cmdlog2);
            Group_RTB_Log_Cmd.Add(Cmdlog3);
            Group_RTB_Log_Cmd.Add(Cmdlog4);
            Group_RTB_Log_Cmd.Add(Cmdlog5);
            Group_TB_Package.Add(load_DFT);
            Group_TB_Package.Add(load_Product);
            Group_TB_Package.Add(load_DFT_size);
            Group_TB_Package.Add(load_Product_size);
            Group_TB_MES.Add(station);
            Group_TB_MES.Add(username);
            Group_TB_MES.Add(plan);
            Group_TB_MES.Add(line);
            Group_TB_MES.Add(banzu);
            Group_TB_FtpServer.Add(ftp_server_ip);
            Group_TB_FtpServer.Add(ftp_server_port);
            Group_TB_FtpServer.Add(ftp_username);
            Group_TB_FtpServer.Add(ftp_password);
            Group_TB_FtpServer.Add(ftp_path);
            Group_CB_Management.Add(is_input_barcode);
            Group_CB_Management.Add(is_MES_pass_station);
            Group_CB_Management.Add(is_auto_save_log);
            Group_CB_Management.Add(is_show_debug_info);
            Group_RB_ProductIP.Add(ip_1);
            Group_RB_ProductIP.Add(ip_2);
            Group_RB_ProductIP.Add(ip_3);
            Group_TB_SSH.Add(login_username);
            Group_TB_SSH.Add(login_passwords);
            Group_TB_SSH.Add(login_default_password);
            Group_TB_SSH.Add(login_password_correct);
            for (int i = 0; i< ThreadNum; i++)
            {
                Group_Input_Barcode.Add("###");
            }
            
        }
        /// <summary>
        /// 初始化界面赋值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            //界面赋值
            //选项卡
            tabControl1.SelectedIndex = Convert.ToInt32(Setting.UserOper["main"]["select_tabControl"]);
            //取消掉Debug选项卡
            tabControl1.TabPages.Remove(Debug);
            //公共线程
            //给选择机柜赋值
            foreach (var item in Setting.IP)
            {
                foreach (var item2 in Group_CB_Cabinet)
                {
                    item2.Items.Add(item["cabinet"]);
                }
            }
            //选择的几号柜
            foreach (var item in Group_CB_Cabinet)
            {
                item.SelectedIndex = Convert.ToInt32(Setting.UserOper["thread"][item.Name]);
            }
            //哪一种IP
            Group_RB_ProductIP[int.Parse(Setting.UserOper["load_software"]["product_IP_type"])].Checked = true;
            //服务器加包
            is_load.Checked = Convert.ToBoolean(Setting.UserOper["load_software"]["is_load"]);
            load_service.Enabled = is_load.Checked;
            ComboxSetValue(load_service, Setting.UserOper["load_software"]["load_service"], Setting.UserOper["load_software"]["load_service_index"]);
            foreach (var item in Group_TB_Package)
            {
                item.Text = Setting.UserOper["load_software"][item.Name];
            }
            //MES设置
            foreach (var item in Group_TB_MES)
            {
                item.Text = Setting.UserOper["mes"][item.Name];
            }
            ComboxSetValue(mes, Setting.UserOper["mes"]["mes"], Setting.UserOper["mes"]["mes_index"]);
            //AP_SSH密码
            foreach (var item in Group_TB_SSH)
            {
                item.Text = Setting.UserOper["AP_SSH"][item.Name];
            }
            //FTP服务器设置
            foreach (var item in Group_TB_FtpServer)
            {
                item.Text = Setting.UserOper["ftp_server"][item.Name];
            }
            button9.Enabled = true;
            button14.Enabled = false;
            //管理员
            foreach (var item in Group_CB_Management)
            {
                item.Checked = Convert.ToBoolean(Setting.UserOper["management"][item.Name]);
            }
           
            //读取流程
            if (Convert.ToBoolean(Setting.UserOper["flow"]["flow_is_default_read"]))
            {
                Prepare(this, null);
            }
        }
        /// <summary>
        /// 界面保存值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //界面的值保存
            Setting.UserOper["main"]["select_tabControl"] = tabControl1.SelectedIndex.ToString();
            //选择的几号柜
            foreach (var item in Group_CB_Cabinet)
            {
                Setting.UserOper["thread"][item.Name] = item.SelectedIndex.ToString();
            }
            //是哪一种IP类型
            for (var i = 0;i< Group_RB_ProductIP.Count;i++)
            {
                if (Group_RB_ProductIP[i].Checked)
                {
                    Setting.UserOper["load_software"]["product_IP_type"] = i.ToString();
                }
            }
            //服务器加包
            Setting.UserOper["load_software"]["is_load"] = is_load.Checked.ToString();
            Setting.UserOper["load_software"]["load_service_index"] = load_service.SelectedIndex.ToString();
            foreach (var item in Group_TB_Package)
            {
                Setting.UserOper["load_software"][item.Name] = item.Text.Trim();
            }
            //MES设置
            foreach (var item in Group_TB_MES)
            {
                Setting.UserOper["mes"][item.Name] = item.Text.Trim();
            }
            Setting.UserOper["mes"]["mes_index"] = mes.SelectedIndex.ToString();
            //AP_SSH密码
            foreach (var item in Group_TB_SSH)
            {
                Setting.UserOper["AP_SSH"][item.Name] = item.Text.Trim();
            }
            //ftp服务器
            foreach (var item in Group_TB_FtpServer)
            {
                Setting.UserOper["ftp_server"][item.Name] = item.Text.Trim();
            }
            //管理员
            foreach (var item in Group_CB_Management)
            {
                Setting.UserOper["management"][item.Name] = item.Checked.ToString();
            }



            //序列化json并保存
            string temp = JsonConvert.SerializeObject(Setting);
            File.WriteAllText(SettingPath, temp);
        }

        /// <summary>
        /// 拆解data值，用";"分割，然后赋值给combox。并且选择index个位置
        /// </summary>
        /// <param name="comboBox"></param>
        /// <param name="data"></param>
        /// <param name="index"></param>
        private void ComboxSetValue(ComboBox comboBox, string data, string index = "0")
        {
            string[] temps = data.Trim().Split(';');
            foreach (var item in temps)
            {
                comboBox.Items.Add(item);
            }
            comboBox.SelectedIndex = Convert.ToInt32(index.Trim());
        }
        /// <summary>
        /// 将combox值每个子项item保存下来
        /// </summary>
        /// <param name="comboBox"></param>
        /// <returns></returns>
        private string ComboxSaveValue(ComboBox comboBox)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in comboBox.Items)
            {
                sb.Append(item.ToString());
                sb.Append(";");
            }
            sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }
        #endregion

        #region 【系统设置】
        /// <summary>
        /// 选择类别时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void select_one(object sender, EventArgs e)
        {
            select_Flow.Items.Clear();
            if (OrderNames!=null && OrderNames.Count >0)
            {
                var selectedOrder = select_TypeOrders.Items[select_TypeOrders.SelectedIndex].ToString();
                foreach (var item in OrderNames[selectedOrder])
                {
                    select_Flow.Items.Add(item);
                }
                select_Flow.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// 选择的流程改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void select_two(object sender, EventArgs e)
        {
            if (OrderDes!=null && OrderDes.Count>0)
            {
                var selectedOrder = select_TypeOrders.Items[select_TypeOrders.SelectedIndex].ToString();
                select_Flow_des.Text = OrderDes[selectedOrder][select_Flow.SelectedIndex];
            }
            else
            {
                select_Flow_des.Text = "";
            }
        }

        //---------------服务器加包----------------
        /// <summary>
        /// 是否同源服务器加包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void is_load_CheckedChanged(object sender, EventArgs e)
        {
            load_service.Enabled = is_load.Checked;
        }
        OpenFileDialog openFileDialog = new OpenFileDialog();
        /// <summary>
        /// 选择装备包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Choose_DFT(object sender, EventArgs e)
        {
            openFileDialog.InitialDirectory = @"D:\Hangs\Package"; // 设置初始目录
            openFileDialog.Filter = "DFT files (*DFT*.cc)|*DFT*.cc|All files (*.*)|*.*"; // 设置文件过滤器
            openFileDialog.FilterIndex = 1;
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (openFileDialog.SafeFileName.ToLower().Contains("dft"))
                {
                    //文件路径
                    load_DFT.Text = openFileDialog.SafeFileName;
                    FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
                    load_DFT_size.Text = (fileInfo.Length / 1024).ToString();
                }
                else
                {
                    MsgShow.Error("选择的不是装备包！");
                }
            }
        }
        /// <summary>
        /// 选择产品包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Choose_Product(object sender, EventArgs e)
        {
            openFileDialog.InitialDirectory = @"D:\Hangs\Package"; // 设置初始目录
            openFileDialog.Filter = "cc files (*.cc)|*.cc|All files (*.*)|*.*"; // 设置文件过滤器
            openFileDialog.FilterIndex = 1;
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (openFileDialog.SafeFileName.ToLower().Contains("dft"))
                {
                    MsgShow.Error("选择的不是产品包！请重新选择！");
                }
                else
                {
                    //文件路径
                    load_Product.Text = openFileDialog.SafeFileName;
                    FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
                    load_Product_size.Text = (fileInfo.Length / 1024).ToString();
                }
            }
        }
        /// <summary>
        /// SSH ip类型选择转换时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ip_CheckedChanged(object sender, EventArgs e)
        {
            if ((sender as RadioButton).Checked)
            {
                comboBox1_SelectedIndexChanged(cabinet1, e);
                comboBox1_SelectedIndexChanged(cabinet2, e);
                comboBox1_SelectedIndexChanged(cabinet3, e);
                comboBox1_SelectedIndexChanged(cabinet4, e);
                comboBox1_SelectedIndexChanged(cabinet5, e);
            }
        }

        //---------------FTP服务器----------------
        //FTPServer ftpserver = new FTPServer();
        /// <summary>
        /// 打开FTP服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void FTP_Open(object sender, EventArgs e)
        {
            //FTPServer.ServerIP = ftp_server_ip.Text.Trim();
            //FTPServer.ServerPort = Convert.ToInt32(ftp_server_port.Text.Trim());
            //FTPServer.UserName = ftp_username.Text.Trim();
            //FTPServer.Password = ftp_password.Text.Trim();
            //FTPServer.DirPath = ftp_path.Text.Trim();
            //await ftpserver.Open();
            //ftplog.AppendText("\r\nFTP服务打开");
            //button9.Enabled = false;
            //button15.Enabled = false;
            //button14.Enabled = true;
        }
        /// <summary>
        /// 关闭FTP服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void  FTP_Close(object sender, EventArgs e)
        {
            //await ftpserver.Close();
            //ftplog.AppendText("\r\nFTP服务关闭");
            //button9.Enabled = true;
            //button15.Enabled = true;
            //button14.Enabled = false;
        }
        /// <summary>
        /// 选择FTP路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Choose_FTP_Dir(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "选择FTP服务的文件夹";
            folder.RootFolder = Environment.SpecialFolder.MyComputer;
            if (folder.ShowDialog() == DialogResult.OK)
            {
                ftp_path.Text = folder.SelectedPath;
            }
        }

        #endregion

        #region 【执行工序】
        //---------------线程框----------------
        /// <summary>
        /// 根据控件的名字最后一个字返回对应的索引-线程几
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        private int GetWhichOne(object sender)
        {
            string name = (sender as Control).Name;
            return int.Parse(name[name.Length - 1].ToString()) - 1;
        }
        /// <summary>
        /// 选择机柜
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //获取索引，截取名字的最后一个
            int index = GetWhichOne(sender);
            //根据选择的机柜几获取到IP地址
            var dict = Setting.GetIPFromCabinet(Group_CB_Cabinet[index].Text);
            //赋值客户端地址
            Group_TB_IP_Telnet[index].Text = dict["telnet_client_ip"];
            if (Group_RB_ProductIP[0].Checked)
            {
                Group_TB_IP_SSH[index].Text = dict["ssh_client_ip"];
            }
            else if (Group_RB_ProductIP[1].Checked)
            {
                Group_TB_IP_SSH[index].Text = dict["ssh_client_ip_10"];
            }
            else if (Group_RB_ProductIP[2].Checked)
            {
                Group_TB_IP_SSH[index].Text = dict["ssh_client_ip_20"];
            }
        }
        /// <summary>
        /// 点击线程框，自动跳转到对应的log
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void groupBox_Enter(object sender, EventArgs e)
        {
            int index = GetWhichOne(sender);
            if(logtab.SelectedIndex!= index)
            {
                logtab.SelectedIndex = index;
            }
        }
        /// <summary>
        /// 清空回显
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClearEcho(object sender, EventArgs e)
        {
            int index = GetWhichOne(sender);
            Group_RTB_Log_Flow[index].Text = "";
            Group_RTB_Log_Cmd[index].Text = "";
        }
        //---------------计时----------------
        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime dt = Convert.ToDateTime("00:" + Time1.Text);
            dt = dt.AddSeconds(1);
            Time1.Text = dt.ToString("mm:ss");
        }
        private void timer2_Tick(object sender, EventArgs e)
        {
            DateTime dt = Convert.ToDateTime("00:" + Time2.Text);
            dt = dt.AddSeconds(1);
            Time2.Text = dt.ToString("mm:ss");
        }
        private void timer3_Tick(object sender, EventArgs e)
        {
            DateTime dt = Convert.ToDateTime("00:" + Time3.Text);
            dt = dt.AddSeconds(1);
            Time3.Text = dt.ToString("mm:ss");
        }
        private void timer4_Tick(object sender, EventArgs e)
        {
            DateTime dt = Convert.ToDateTime("00:" + Time4.Text);
            dt = dt.AddSeconds(1);
            Time4.Text = dt.ToString("mm:ss");
        }
        private void timer5_Tick(object sender, EventArgs e)
        {
            DateTime dt = Convert.ToDateTime("00:" + Time5.Text);
            dt = dt.AddSeconds(1);
            Time5.Text = dt.ToString("mm:ss");
        }
        //---------------保存log----------------
        /// <summary>
        /// 保存log
        /// </summary>
        private void SaveLog(int index)
        {
            try
            {
                string dirPath = LogPath;
                dirPath += $@"{DateTime.Now.ToString("yyyy-MM")}\{DateTime.Now.ToString("dd")}\";
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                File.WriteAllText($@"{dirPath}[{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}]{Group_Input_Barcode[index]}_Flow.log", Group_RTB_Log_Flow[index].Text);
                File.WriteAllText($@"{dirPath}[{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}]{Group_Input_Barcode[index]}_Cmd.log", Group_RTB_Log_Cmd[index].Text);
            }
            catch(Exception e)
            {
                MsgShow.Error("保存log出错，具体原因："+e.Message);   
            }
        }
        #endregion

        #region 【执行结果】

        /// <summary>
        /// 选择对应的机柜
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Result_Choose_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Result_Choose.SelectedIndex > 0)
            {
                ResultTB.DataSource = (DataTable)Group_Executors[Result_Choose.SelectedIndex].Running_ResultTB;
            }
            else
            {
                ResultTB.DataSource = null;
            }
        }
        #endregion

        #region 【Debug】
        /// <summary>
        /// 暂停或继续
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Pause5_Click(object sender, EventArgs e)
        {
            int index = GetWhichOne(sender);
            if (Pause5.Text == "暂停")
            {
                Group_Executors[index].Pause();
                Pause5.Text = "继续";
                timer5.Stop();
            }
            else
            {
                Group_Executors[index].GoOn();
                Pause5.Text = "暂停";
                timer5.Start();
            }

        }
        /// <summary>
        /// 清空回显
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            Cmdlog5.Text = "";
            Flowlog5.Text = "";
        }
        /// <summary>
        /// 调试用的执行器
        /// </summary>
        Executor Debug_Executor = null;
        //命令发送界面
        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            Debug_Executor.WindowsCmd_Execute(D_input_cmd.Text);
            Cmdlog5.AppendText($"\r\n——————————————————————————————————————————————————————————————————————\r\n");
            Flowlog5.AppendText($"\r\n-->发送命令：{D_input_cmd.Text}");
            if (clear_cmdbox.Checked)
            {
                D_input_cmd.Text = "";
            }
        }

        /// <summary>
        /// 发送一次还是两次
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (cmd_send_twice.Checked)
            {
                Debug_Executor.WindowsCmd_SendTwice();
            }
            else
            {
                Debug_Executor.WindowsCmd_SendOnce();
            }
        }
        /// <summary>
        /// 启动cmd
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click_1(object sender, EventArgs e)
        {
            Debug_Executor.WindowsCmd_Open();
            Flowlog5.AppendText($"\r\n——————————打开cmd———————————");
            checkBox1_CheckedChanged(null, null);
        }

        //功能区界面



        //文本命令发送界面
        /// <summary>
        /// 打开文本命令文件的路径
        /// </summary>
        private string openFilePath = "";
        /// <summary>
        /// 打开文本文件以备发送命令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button12_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = @"D:\Hangs\Package"; // 设置初始目录
            openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; // 设置文件过滤器
            openFileDialog.FilterIndex = 1;
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //文件路径
                openFilePath = openFileDialog.FileName;
                richTextBox3.Text = File.ReadAllText(openFileDialog.FileName, Encoding.Default);
                D_text_send.Visible = true;
                D_text_save.Visible = true;
                D_text_openfile.Visible = true;
                D_text_reset.Visible = true;
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button21_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(openFilePath))
            {
                File.WriteAllText(openFilePath, richTextBox3.Text, Encoding.Default);
                MsgShow.OK("保存成功");
            }
        }
        /// <summary>
        /// 打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button22_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(openFilePath))
            {
                System.Diagnostics.Process.Start(openFilePath);
            }
        }
        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button23_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(openFilePath))
            {
                richTextBox3.Text = File.ReadAllText(openFilePath, Encoding.Default);
            }
        }
        /// <summary>
        /// 按行发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button13_Click(object sender, EventArgs e)
        {

            int currentIndex = richTextBox3.SelectionStart;
            int currentLine = richTextBox3.GetLineFromCharIndex(currentIndex);

            // 选中当前行
            int startIndex = richTextBox3.GetFirstCharIndexFromLine(currentLine);
            int endIndex = richTextBox3.GetFirstCharIndexFromLine(currentLine + 1);
            if (endIndex != -1)
            {
                richTextBox3.Select(startIndex, endIndex - startIndex);
                richTextBox3.SelectionBackColor = Color.LightSkyBlue;
            }

            // 读取当前行的内容
            D_input_cmd.Text = richTextBox3.SelectedText.Replace("\n", "").Replace("\r", "");
            button2_Click(null, null);

            // 移动到下一行
            if (currentLine + 1 < richTextBox3.Lines.Length)
            {
                int startIndex2 = richTextBox3.GetFirstCharIndexFromLine(currentLine + 1);
                int endIndex2 = richTextBox3.GetFirstCharIndexFromLine(currentLine + 2);
                richTextBox3.Select(startIndex2, endIndex2 - startIndex2);
            }
        }
        /// <summary>
        /// 按下回车键，自动发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void richTextBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button2_Click(null, null);
            }
        }

        /// <summary>
        /// 删除公钥？？是否还有必要？？
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            string path = "C:\\UserOpers\\JSZX-GM0826T1\\.ssh\\known_hosts";
            if (File.Exists(path))
            {
                File.Delete(path);
                //Logging("公钥文件已删除");
            }
            else
            {
                //Logging("公钥文件未找到");
            }
        }

        /// <summary>
        /// 打开脚本文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button16_Click(object sender, EventArgs e)
        {
            string path = Path.GetDirectoryName(Setting.UserOper["flow"]["flow_address"]);
            if (Directory.Exists(path))
            {
                // 如果文件存在
                System.Diagnostics.Process.Start(path);
            }
            else
            {
                if (File.Exists(path))
                {
                    System.Diagnostics.Process.Start(path);
                }
                else
                {
                    // 如果文件不存在
                    MsgShow.Hint("文件或文件夹不存在！", "提示");
                }

            }
        }
        #endregion

        #region 核心程序
        /// <summary>
        /// 输入的barcode
        /// </summary>
        private List<string> Group_Input_Barcode = new List<string>();
        /// <summary>
        /// 流程的描述
        /// </summary>
        private Dictionary<string, List<string>> OrderNames = new Dictionary<string, List<string>>();
        private Dictionary<string, List<string>> OrderDes = new Dictionary<string, List<string>>();

        /// <summary>
        /// 读取流程，并传递相应的变量和注册相应的事件
        /// </summary>       
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Prepare(object sender, EventArgs e)
        {
            InitialExecutor initialExecutor = new InitialExecutor(this);
            //初始化
            initialExecutor.P1_LoadFile(Setting.UserOper["flow"]["flow_address"]);
            //为order赋值
            OrderNames = initialExecutor.NamesByOrderNameOnDisplay;
            OrderDes = initialExecutor.DesByOrderNameOnDisplay;
            //赋初值
            select_TypeOrders.Items.Clear();
            foreach (var item in initialExecutor.OrderFileNameOnDisplay) 
            {
                select_TypeOrders.Items.Add(item);
            }
            select_TypeOrders.SelectedIndex = 0;
            for (int j = 0; j < ThreadNum; j++)
            {
                //闭包变量暂留
                int i = j;
                //给执行器赋值
                Group_Executors.Add(new Executor(this, initialExecutor, i));
                Group_Executors[i].This_ProgressBar = Group_PB[i];
                //展示flowlog
                Group_Executors[i].Action_WriteFlowLog = (msg) =>
                {
                    Group_RTB_Log_Flow[i].AppendText(msg + "\r\n");
                    Group_RTB_Log_Flow[i].ScrollToCaret();
                };
                //展示cmdLog
                Group_Executors[i].Action_WriteCmdLog = (msg) =>
                {
                    Group_RTB_Log_Cmd[i].AppendText(msg);
                    if (!msg.EndsWith("\r\n"))
                    {
                        Group_RTB_Log_Cmd[i].AppendText("\r\n");
                    }
                    Group_RTB_Log_Cmd[i].ScrollToCaret();
                };
                //展示进度值
                Group_Executors[i].Prg_ShowValue = (value) =>
                {
                    Group_LB_ProgressValue[i].Text = value.ToString();
                };
                //开始时，界面的操作
                Group_Executors[i].Action_Start = () =>
                {
                    Group_BT_Start[i].Enabled = false;
                    Group_BT_Stop[i].Enabled = true;
                    Group_LB_TimeCount[i].Text = "00:00";
                    Group_Timer[i].Enabled = true;
                };
                //结束时，界面的操作
                Group_Executors[i].Action_End = () =>
                {
                    Group_Timer[i].Enabled = false;
                    Group_BT_Start[i].Enabled = true;
                    Group_BT_Stop[i].Enabled = false;
                    if (i == 4)
                    {
                        Pause5.Enabled = false;
                    }
                    //如果需要保存日志
                    if (is_auto_save_log.Checked)
                    {
                        SaveLog(i);
                    }
                    //mes过站
                    if (is_MES_pass_station.Checked)
                    {
                        Mes_Out(i);
                    }
                };
                //用户停止时，界面的操作
                Group_Executors[i].Action_Stop = () =>
                {
                    Group_Timer[i].Enabled = false;
                    Group_BT_Start[i].Enabled = true;
                    Group_BT_Stop[i].Enabled = false;
                    Group_LB_ProgressValue[i].Text = "STOP";
                    if (i==4)
                    {
                        Pause5.Enabled = false;
                    }
                    //如果需要保存日志
                    if (is_auto_save_log.Checked)
                    {
                        SaveLog(i);
                    }
                };
            }
            //最后一个是调试用的
            Debug_Executor = Group_Executors[4];
            //执行下一条命令时，界面的先前操作
            Debug_Executor.Action_ExeNextCmd = (k) =>
            {
                CountCmd.Visible = true;
                CountCmd.Text = "NO."+k.ToString();
            };
        }
        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Start(object sender, EventArgs e)
        {
            int index = GetWhichOne(sender);
            if (is_input_barcode.Checked && index != 4)
            {
                //展示输入框
                Input_Barcode ib = new Input_Barcode(index);
                ib.CheckBarcode = (barcode) =>
                {
                    return Regex.IsMatch(barcode, Setting.UserOper["main"]["barcode_check"]);
                };
                ib.SuccessAction = (barcode) =>
                {
                    Group_Input_Barcode[index] = barcode;

                    ClearEcho(sender, e);
                    //mes过站
                    if (is_MES_pass_station.Checked)
                    {
                        if (Mes_In(index))
                        {
                            Executing(index);
                        }
                    }
                    else
                    {
                        Executing(index);
                    }
                };
                ib.ShowDialog();
            }
            else
            {
                Group_Input_Barcode[index] = "###";
                if (index == 4)
                {
                    Group_Input_Barcode[index] = "Debug";
                }
                ClearEcho(sender, e);
                Executing(index);
            }
            //调试界面
            if (index==4)
            {
                Pause5.Enabled = true;
            }
        }
        /// <summary>
        /// 收集变量信息，传递给执行器
        /// </summary>
        private void Collect_Info(int index)
        {
            Group_Executors[index].IsPrintDebugInfo = is_show_debug_info.Checked;
            var dict = Group_Executors[index].Params_InCmd;

            dict.Clear();
            dict["$$thread_index$$"] = index.ToString();
            
            dict["$$ftp_server_ip$$"] = ftp_server_ip.Text;
            dict["$$ftp_server_port$$"] = ftp_server_port.Text;
            dict["$$ftp_username$$"] = ftp_username.Text;
            dict["$$ftp_password$$"] = ftp_password.Text;
            
            dict["$$load_DFT$$"] = load_DFT.Text;
            dict["$$load_DFT_size$$"] = load_DFT_size.Text;
            
            dict["$$load_Product$$"] = load_Product.Text;
            dict["$$load_Product_size$$"] = load_Product_size.Text;
            
            dict["$$telnet_client_ip$$"] = Group_TB_IP_Telnet[index].Text;
            dict["$$ssh_client_ip$$"] = Group_TB_IP_SSH[index].Text;

            //ssh登录用户名和密码
            dict["$$ssh_username$$"] = login_username.Text.Trim();
            dict["$$ssh_password$$"] = login_default_password.Text.Trim();
            var t = login_passwords.Text.Trim().Split('\n');
            for (int i = 0; i < t.Length; i++)
            {
                dict[$"$$ssh_password{i}$$"] = t[i].Trim();
            }
            dict["$$ssh_password_correct$$"] = login_password_correct.Text.Trim();

            //输入的整机条码
            dict["$$input_machine_barcode$$"] = Group_Input_Barcode[index];
        }
        /// <summary>
        /// 执行流程
        /// </summary>
        /// <param name="index"></param>
        private void Executing(int index)
        {
            //收集变量值
            Collect_Info(index);
            //根据流程的名字，开始执行
            Group_Executors[index].Start(select_Flow.Text);
        }
        /// <summary>
        /// 停止流程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Stop(object sender, EventArgs e)
        {
            int index = GetWhichOne(sender);
            //调试界面
            if (index == 4)
            {
                Pause5.Enabled = false;
            }
            Group_Executors[index].Stop();
        }
        /// <summary>
        /// mes入站
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private bool Mes_In(int index)
        {
            string planName = "", errMsg = "";
            IMes_PassStation ontMes = new OntMes();
            ontMes.GetPlanName(Group_Input_Barcode[index], ref planName, ref errMsg);
            Dictionary<MesName, string> input = new Dictionary<MesName, string>();
            input[MesServices.MesName.Line] = line.Text.Trim();
            input[MesServices.MesName.Plan] = planName.Trim();
            input[MesServices.MesName.SN] = Group_Input_Barcode[index].Trim();
            input[MesServices.MesName.Station] = station.Text.Trim();
            input[MesServices.MesName.UserName] = username.Text.Trim();
            input[MesServices.MesName.Platform] = "ATEGO".Trim();
            input[MesServices.MesName.Equipment] = select_Flow.Text;
            bool res = ontMes.BeforeTest(input, ref errMsg);
            if (!res)
            {
                MsgShow.Error("入站失败：" + errMsg, $"线程{index}");
            }
            return res;
        }
        /// <summary>
        /// mes过站
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private bool Mes_Out(int index)
        {
            string planName = "", errMsg = "";
            IMes_PassStation ontMes = new OntMes();
            ontMes.GetPlanName(Group_Input_Barcode[index], ref planName, ref errMsg);
            Dictionary<MesName, string> input = new Dictionary<MesName, string>();
            input[MesServices.MesName.Line] = line.Text.Trim();
            input[MesServices.MesName.Plan] = planName.Trim();
            input[MesServices.MesName.SN] = Group_Input_Barcode[index].Trim();
            input[MesServices.MesName.Station] = station.Text.Trim();
            input[MesServices.MesName.UserName] = username.Text.Trim();
            input[MesServices.MesName.Platform] = "ATEGO";
            input[MesServices.MesName.Equipment] = select_Flow.Text;
            input[MesServices.MesName.Result] = "true";
            bool res = ontMes.AfterTest(input, ref errMsg);
            if (!res)
            {
                MsgShow.Error("过站失败：" + errMsg, $"线程{index}");
            }
            return res;
        }
        #endregion

        #region 权限模式
        /// <summary>
        /// 是否打开了权限模式
        /// </summary>
        private bool isDiagnose = false;
        /// <summary>
        /// 按下ctrl+a打开权限模式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ATEGO_KeyDown(object sender, KeyEventArgs e)
        {
            if (!isDiagnose && e.Control && e.KeyCode == Keys.A)
            {
                Input_Password ip = new Input_Password(Setting.UserOper["diagnose"]["dgn_password"]);
                ip.SuccessAction = () =>
                {
                    //tabControl1.SelectedIndex = 1;
                    isDiagnose = true;
                    CommanderSetting.Visible = true;
                    
                    station.Enabled = true;
                    mes.Enabled = true;
                    tabControl1.TabPages.Add(Debug);
                };
                ip.ShowDialog();
            }
            //ESC退出诊断模式
            else if (isDiagnose && e.KeyCode == Keys.Escape)
            {
                isDiagnose = false;
                CommanderSetting.Visible = false;
                
                station.Enabled = false;
                mes.Enabled = false;
                tabControl1.TabPages.Remove(Debug);
            }
        }
        #endregion


        /// <summary>
        /// Mes调用示例
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button29_Click(object sender, EventArgs e)
        {
            string planName = "", errMsg = "";
            IMes_PassStation ontMes = new OntMes();
            ontMes.GetPlanName("2150086767LDQ6000601", ref planName, ref errMsg);
            //MESHelperSoapClient mesHelperSoapClient = new MESHelperSoapClient();
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            string path = Path.GetDirectoryName(Setting.UserOper["main"]["log"]);
            if (Directory.Exists(path))
            {
                // 如果文件存在
                System.Diagnostics.Process.Start(path);
            }
            else
            {
                if (File.Exists(path))
                {
                    System.Diagnostics.Process.Start(path);
                }
                else
                {
                    // 如果文件不存在
                    MsgShow.Hint("文件或文件夹不存在！", "提示");
                }

            }
        }
    }
}
